package com.tanhua.dubbo.api;

import cn.hutool.core.collection.CollUtil;
import com.tanhua.model.mongo.Friend;
import com.tanhua.model.mongo.RecommendUser;
import com.tanhua.model.mongo.UserLike;
import com.tanhua.model.vo.PageResult;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.aggregation.TypedAggregation;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.ArrayList;
import java.util.List;

@DubboService
public class RecommendUserAPiImpl implements RecommendUserApi{

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 查询今日佳人
     * @param userId
     * @return
     */
    @Override
    public RecommendUser queryWithMaxScore(Long userId) {
        //根据toUserId查询，根据评分score排序，第一条即为分数最高的数据，获取第一条
        //构建Criteria
        Criteria criteria = Criteria.where("toUserId").is(userId);
        //构建query对象
        Query query = Query.query(criteria).with(Sort.by(Sort.Order.desc("score")))
                .limit(1);

        return mongoTemplate.findOne(query,RecommendUser.class);
    }

    /**
     * 查询推荐好友
     * @param toUserId
     * @param page
     * @param pagesize
     * @return
     */
    @Override
    public PageResult queryByPageAndUserId(Long toUserId, Integer page, Integer pagesize) {
        //构建Criteria对象
        Criteria criteria = Criteria.where("toUserId").is(toUserId);
        //构建Query对象
        Query query = Query.query(criteria);
        //查询总数
        long count = mongoTemplate.count(query, RecommendUser.class);
        //查询数据列表
        query.with(Sort.by(Sort.Order.desc("score"))).limit((page-1)*pagesize).skip(pagesize);
        List<RecommendUser> recommendUsers = mongoTemplate.find(query, RecommendUser.class);

        //构造返回对象
        PageResult pr  = new PageResult(page,pagesize,count,recommendUsers);

        return pr;
    }


    /**
     * 查询好友，返回好友ID列表
     */
    @Override
    public List<Long> findFriendIDs(Long id) {
        Criteria criteria = Criteria.where("userId").is(id);
        Query query = Query.query(criteria).with(Sort.by(Sort.Order.desc("created")));
        List<Friend> friends = mongoTemplate.find(query, Friend.class);
        List<Long> idList = new ArrayList<>();
        for (Friend friend : friends) {
            idList.add(friend.getFriendId());
        }
        return idList;
    }

    @Override
    public RecommendUser queryByUserId(Long id, Long toUserId) {
        Query query = Query.query(Criteria.where("userId").is(id).and("toUserId").is(toUserId));
        RecommendUser user = mongoTemplate.findOne(query, RecommendUser.class);
        if (user == null){
            user = new RecommendUser();
            user.setUserId(id);
            user.setToUserId(toUserId);
            user.setScore(97d);
        }
        return user;
    }

    /**
     * 探花-查询推荐用户列表
     * 1.排除已经喜欢/不喜欢的用户
     * 2.随机展示
     * 3.指定数量
     * @param userId：当前用户的ID
     * @param counts：指定查询的数量
     * @return
     */
    @Override
    public List<RecommendUser> cardList(Long userId, int counts) {
        //查询user_like表中已经喜欢或者不喜欢的用户，获取他们的id
        List<UserLike> likeList = mongoTemplate.find(Query.query(Criteria.where("userId").is(userId)), UserLike.class);
        List<Long> likeUserIds = CollUtil.getFieldValues(likeList, "likeUserId", Long.class);
        //构建查询推荐用户的条件，排除已经喜欢或者不喜欢的用户
        Criteria criteria = Criteria.where("toUserId").is(userId).and("userId").nin(likeUserIds);
        //使用统计函数，随机获取推荐的用户列表
        TypedAggregation<RecommendUser> typedAggregation = TypedAggregation.newAggregation(RecommendUser.class,
                Aggregation.match(criteria),    //指定条件
                Aggregation.sample(counts));//指定随机获取的数量
        AggregationResults<RecommendUser> result = mongoTemplate.aggregate(typedAggregation, RecommendUser.class);
        //构造返回数据，只需要获取里面的用户数据即可
        List<RecommendUser> list = result.getMappedResults();
        return list;
    }
}
